package com.atguigu.myjuc.locks;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * 死锁
 * 自己持有A锁，尝试获得B锁，自己持有B锁，尝试获得A锁这种现象就会发生死锁
 */
public class DeadLockDemo {
    static Lock lockA = new ReentrantLock();
    static Lock lockB = new ReentrantLock();

    public static void main(String[] args) {
        new Thread(() -> {
            lockA.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "\t" + "自己持有A锁，尝试获得B锁");
                lockB.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "\t" + "成功获得B锁");
                } finally {
                    lockB.unlock();
                }
            } finally {
                lockA.unlock();
            }
        },"A").start();

        new Thread(() -> {
            lockB.lock();
            try {
                System.out.println(Thread.currentThread().getName()+"\t"+"自己持有B锁，尝试获得A锁");
                try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
                lockA.lock();
                try {
                    System.out.println(Thread.currentThread().getName()+"\t"+"成功获得A锁");
                }finally {
                    lockA.unlock();
                }
            }finally {
                lockB.unlock();
            }
        },"B").start();
    }
}
